package com.guilang.localmusic;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MusicPlayer extends AppCompatActivity implements View.OnClickListener {
    private String Sname, Ssinger, Surl;
    private int Simage, Sduration;
    private TextView songName, songSinger, songTime, currentTime;
    private ImageView imageView;
    private ImageButton play, next, pause, previous, stop;
    private SeekBar seekBar;
    private View view;
    private List<SongItem> Items;
    private int position;  //记录播放位置

    private final MediaPlayer mediaPlayer = new MediaPlayer();
    private AudioManager audioManager;//调节音量之类的Manager
    private final int currentPosition = 0; //当前音乐进度
    private boolean isSeekBarChanging;
    private Timer timer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        ActivityCollector.addActivity(this);
        Toolbar toolbar = findViewById(R.id.MusicPlayer_Toolbar);
        setSupportActionBar(toolbar);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayShowTitleEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.ic_arrow_down);
        }
        Intent intent = getIntent();

        songName = findViewById(R.id.Player_song_name);  //音乐名
        imageView = findViewById(R.id.Player_song_image);//封面
        songSinger = findViewById(R.id.Player_song_singer);//歌手
        songTime = findViewById(R.id.endTime);           //时长
        currentTime = findViewById(R.id.startTime);
        play = findViewById(R.id.MusicPlayer_play);
        next = findViewById(R.id.MusicPlayer_next);
        previous = findViewById(R.id.MusicPlayer_previous);
        stop = findViewById(R.id.MusicPlayer_stop);
        seekBar = findViewById(R.id.seekBar);

        //设置界面信息
        Sname = intent.getStringExtra("Sname");
        Ssinger = intent.getStringExtra("Ssinger");
        Simage = intent.getIntExtra("Simage", R.mipmap.avater);
        Surl = intent.getStringExtra("Surl");
        Sduration = intent.getIntExtra("Sduration", 0);
        Items = (ArrayList<SongItem>) getIntent().getSerializableExtra("songlist");
        position = intent.getIntExtra("Sposition", 0);

        RefreshUI(Items.get(position));
        //设置按钮监听
        play.setOnClickListener(MusicPlayer.this);
        next.setOnClickListener(MusicPlayer.this);
        previous.setOnClickListener(MusicPlayer.this);
        stop.setOnClickListener(this);
        //音乐管理服务
        audioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
        initMediaPlayer(Surl);
        playMusic(); //自动开始播放

    }

    //初始化音乐播放
    private void initMediaPlayer(String Surl) {
        try {
            mediaPlayer.setDataSource(Surl);
            mediaPlayer.prepare();
            mediaPlayer.setLooping(false);
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    seekBar.setMax(Sduration);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //播放音乐
    private void playMusic() {
        if (!mediaPlayer.isPlaying()) {
            mediaPlayer.start();
            mediaPlayer.seekTo(currentPosition);
        }
        updateSeekBar();
    }


    //界面更新
    private void RefreshUI(SongItem songItem) {
        Sname = songItem.getSongName();
        Ssinger = songItem.getSinger();
        Simage = songItem.getSongImage();
        Surl = songItem.getSongUrl();
        Sduration = songItem.getSongDuration();

        songName.setText(Sname);
        songSinger.setText(Ssinger);
        imageView.setImageResource(Simage);
        songTime.setText(formatTime(Sduration));
    }


    //SeekBar更新
    private void updateSeekBar() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            final Runnable updateUI = new Runnable() {
                @Override
                public void run() {
                    //更新进度条
                    int time = mediaPlayer.getCurrentPosition();
                    currentTime.setText(formatTime(time));
                }
            };

            @Override
            public void run() {
                if (!isSeekBarChanging) {
                    seekBar.setProgress(mediaPlayer.getCurrentPosition());
                    runOnUiThread(updateUI);
                }
            }
        }, 0, 50);
    }

    //Toolbar各按钮的点击事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            default:
                break;
        }
        return true;
    }

    //点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.MusicPlayer_next:
                int pos = -1;
                if (Items != null) {
                    if (position == Items.size() - 1) {
                        pos = position = 0;
                    } else {
                        pos = ++position;
                    }
                }
                mediaPlayer.reset();
                initMediaPlayer(Items.get(pos).getSongUrl());
                RefreshUI(Items.get(pos));
                playMusic();
                break;
            case R.id.MusicPlayer_previous:
                int posi = -1;
                if (Items != null) {
                    if (position == 0) {
                        posi = Items.size() - 1;
                    } else {
                        posi = --position;
                    }
                }
                mediaPlayer.reset();
                initMediaPlayer(Items.get(posi).getSongUrl());
                RefreshUI(Items.get(posi));
                playMusic();
                break;
            case R.id.MusicPlayer_stop:
                if (timer != null) {
                    timer.cancel();
                    timer = null;
                }
                if (mediaPlayer.isPlaying()) {
                    Toast.makeText(MusicPlayer.this, "Click", Toast.LENGTH_SHORT).show();
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                    initMediaPlayer(Items.get(position).getSongUrl());
                }


                break;
            case R.id.MusicPlayer_play:
                playMusic();
                break;
            default:
                break;
        }

    }

    //格式化时间
    public static String formatTime(int time) {
        String min = time / (1000 * 60) + "";
        String sec = time % (1000 * 60) + "";
        if (min.length() < 2) {
            min = "0" + time / (1000 * 60) + "";
        } else {
            min = time / (1000 * 60) + "";
        }
        if (sec.length() == 4) {
            sec = "0" + (time % (1000 * 60)) + "";
        } else if (sec.length() == 3) {
            sec = "00" + (time % (1000 * 60)) + "";
        } else if (sec.length() == 2) {
            sec = "000" + (time % (1000 * 60)) + "";
        } else if (sec.length() == 1) {
            sec = "0000" + (time % (1000 * 60)) + "";
        }
        return min + ":" + sec.trim().substring(0, 2);
    }

//    @Override
//    protected void onPause() {
//        super.onPause();
//        if (mediaPlayer.isPlaying()) {
//            mediaPlayer.pause();
//        }
//    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //timer得在mediaplayer之前停止
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
        ActivityCollector.removeActivity(this);
    }
}
